package com.service.img;

import com.domain.HttpResponse;
import com.domain.ex.BizException;
import com.domain.ex.Codes;
import com.utils.ConfigUtils;
import com.utils.ImgUploadUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.IOException;

/**
 * Created by Administrator on 2016/1/10 0010.
 */
@Service
public class ImgServiceImpl implements ImgService {


    @Override
    public Object uploadImg(CommonsMultipartFile file) {


        if (file.getSize() > Long.valueOf(ConfigUtils.getString("ImgMaxSize"))){
            return HttpResponse.create(Codes.ImgSizeError);
        }

        if (file.isEmpty()) {
            return HttpResponse.create(Codes.FileNotFound);
        }
        String OriginalFilename = file.getOriginalFilename();
        if (StringUtils.isBlank(OriginalFilename)) {
            throw BizException.create(Codes.FileNotFound);
        }
        Object obj = null;
        FileItem fileItem = file.getFileItem();
        if (!"jpg".equalsIgnoreCase(OriginalFilename.substring(OriginalFilename.lastIndexOf(".") + 1))
                && !"jpeg".equalsIgnoreCase(OriginalFilename.substring(OriginalFilename.lastIndexOf(".") + 1))
                && !"png".equalsIgnoreCase(OriginalFilename.substring(OriginalFilename.lastIndexOf(".") + 1))
                && !"bmp".equalsIgnoreCase(OriginalFilename.substring(OriginalFilename.lastIndexOf(".") + 1))
                ) {
            throw BizException.create(Codes.NotImg, "JPG/JPEG/PNG/BMP");
        }
        try {
            obj = ImgUploadUtils.uploadImgByQclound(fileItem.getInputStream());
        } catch (IOException e) {
            throw BizException.create(Codes.FileUploadError,e.getMessage());
        }
        Object object = HttpResponse.create(Codes.OK,"",obj);
        return object;
    }


}
